package apis

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"time"
	apisadmin "tuowei.com/app/admin/apis"
	dto2 "tuowei.com/app/admin/service/dto"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysCourse struct {
	api.Api
	Base
}

func (e SysCourse) GetPages(c *gin.Context) {
	s := service.SysScore{}
	req := dto.SysScoreGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(c)
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	var count int64
	list := make([]models.SysScore, 0)

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func setWatchKey(studentId, courseId, chapterId int) string {
	return fmt.Sprintf("sys_course_watch_progres_%d_%d_%d", studentId, courseId, chapterId)
}

// 设置观看进度，这种东西一般来说设置半个月就足够了
// courseId 课程id
// completed 是否完成
// duration 已观看时长，秒
func setWatchProgress(studentId, courseId int, completed bool, duration, chapterId int) error {
	key := setWatchKey(studentId, courseId, chapterId)
	if !completed {
		return config.GetRedisClient().Set(key, duration, time.Hour*24*15).Err()
	} else {
		return config.GetRedisClient().Del(key).Err()
	}
}

func (e SysCourse) Watch(ctx *gin.Context) {
	//ParseToken
	req := dto2.SysCourseWatch{}
	s := service.ApiCourse{}
	err := e.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = setWatchProgress(studentId, req.CourseId, req.Completed, req.Duration, req.ChapterId)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "ok")
}
func (e SysCourse) Get(c *gin.Context) {
	//无用
	s := service.SysScore{}
	req := dto.SysScoreGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//在线课程详情不做token，分享的页面不传buyid
	cou := apisadmin.SysCourse{}

	// 写的一坨屎,好球难读，两个req？？？
	result, err := cou.GetInternal(c, req.BuyerId)
	if err != nil {
		e.Error(http.StatusInternalServerError, err, "查询失败")
		return
	}
	e.OK(result, "查询成功")
}
